package com.hezhou.oauth2.web.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hezhou.oauth2.web.entities.SysPermission;
import com.hezhou.oauth2.web.entities.SysRole;
import com.hezhou.oauth2.web.mapper.SysPermissionMapper;
import com.hezhou.oauth2.web.mapper.SysRoleMapper;
import com.hezhou.oauth2.web.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * ---------------------------
 * (SysRoleServiceImpl) 系统角色逻辑实现层
 * ---------------------------
 *
 * @Author: [hezhou]
 * @Date: 2020/3/6
 * @Version: [1.0.1]
 * ---------------------------
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Autowired
    private SysPermissionMapper sysPermissionMapper;

    /**
     * 实现分页模糊查询权限名
     * @param page 分页对象
     * @param sysRole 条件查询对象
     * @return
     */
    @Override
    public IPage<SysRole> selectPage(Page<SysRole> page, SysRole sysRole) {
        IPage<SysRole> sysRoleIPage = baseMapper.selectPage(page, sysRole);
        return sysRoleIPage;
    }

    /**
     * 查询角色拥有的权限
     * @param roleId
     * @return
     */
    @Override
    public SysRole selectRolePermission(Long roleId) {
        //防止包空指针
        if (roleId == null){
          return new SysRole();
        }
        //查询角色的权限信息
        List<SysPermission> rolePermissionById = sysPermissionMapper.findRolePermissionById(roleId);
        SysRole sysRole = baseMapper.selectById(roleId);
        //查询角色信息
        if (sysRole != null){
            sysRole.setPerList(rolePermissionById);
        }
        return sysRole;
    }

    @Transactional
    @Override
    public Boolean deleteById(Long id) {
        try{
            Boolean aBoolean = baseMapper.deleteRolePermissionById(id);
        if (aBoolean){
            baseMapper.deleteById(id);
        }}catch (Exception e){
            e.printStackTrace();
        }
        return true;
    }

    @Transactional
    @Override
    public boolean saveOrUpdate(SysRole entity) {
        try {
            entity.setUpdateDate(new Date());
            boolean b = super.saveOrUpdate(entity);
            if (b == true) {
                baseMapper.deleteRolePermissionById(entity.getId());
                baseMapper.batchInsertRolePermission(entity.getId(), entity.getPerIds());
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return true;
    }

}
